var map;
var features;
var featureOverlay;
//当前选择
var selectObj=new Object();
selectObj.id="";
selectObj.name="";
selectObj.type="";
selectObj.selected=false;
//绘制区域
var regionObj=new Object();
regionObj.layer=null;
regionObj.interaction=null;
//中心点图层
var centerPointObj=new Object();
centerPointObj.layer=null;
centerPointObj.interaction=null;
//基站图层
var baseStationObj=new Object();
baseStationObj.layer=null;
baseStationObj.interaction=null;
//激活器图层
var activatorObj=new Object();
activatorObj.layer=null;
activatorObj.interaction=null;
//选择颜色
var selectStyle = new ol.style.Style({
    fill: new ol.style.Fill({ //矢量图层填充颜色，以及透明度
        color: 'rgba(0, 0, 255, 0.15)'
        //color: 'rgba(0, 0, 255, 0.4)'
    }),
    stroke: new ol.style.Stroke({ //边界样式
        color: '#01f6ff',
        width: 3
    }),
    text: new ol.style.Text({ //文本样式
        font: '18px Calibri,sans-serif',
        fill: new ol.style.Fill({
            color: '#000'
        }),
        stroke: new ol.style.Stroke({
            color: '#fff',
            width: 3
        }) ,
        offsetX:-5,
        offsetY:25
    })
    ,
    image: new ol.style.Icon(/** @type {olx.style.IconOptions} */ ({
        src: $("#contextPath").val()+'/userfiles/points/select32.png'
    }))
});
$(function() {
    console.info("地图配置 currentSelectTiles="+JSON.stringify(currentSelectTiles));
    //查找区域列表
    listRegionsCombobox();

    if(currentSelectTiles.name){
        $("#mapName").html("当前地图："+currentSelectTiles.name);
    }else{
        $("#mapName").html("当前地图：");
    }
	//初始化地图
    map = new ol.Map({
        layers : [ new ol.layer.Tile({
            source : new ol.source.XYZ({
                //url :  '/zhsq/userfiles/20180830222423_1/4-6/{z}/{x}/{y}.png'
                url :  $("#contextPath").val()+currentSelectTiles.tilesPath+'/4-6/{z}/{x}/{y}.png'

            })
            // source: new ol.source.OSM()
        }) ],
        controls : ol.control.defaults({
            attributionOptions : /** @type {olx.control.AttributionOptions} */
                ({
                    collapsible : false
                })
        }),
        logo : false,// 取消logo
        target : 'map',
        view : new ol.View({
            projection : 'EPSG:4326',
            center : [ 33.74975, 0 ],
            extent : [ 0, -21.94, 67.4995, 21.94 ],
            // center: ol.proj.transform([15,15], 'EPSG:4326', 'EPSG:3857'),
            // extent:ol.proj.transform([10,10, 20,20], 'EPSG:4326', 'EPSG:3857'),
            zoom : 4,
            minZoom : 4,
            maxZoom : 6
        })
    });
    //鼠标显示经纬度
    var mousePositionControl=new ol.control.MousePosition({
        coordinateFormat:ol.coordinate.createStringXY(4),
        projection:"EPSG:4326",
        className:"custom-mouse-position",
        target:document.getElementById("mouse-position"),
        undefinedHTML:"&nbsp",

    });
    map.addControl(mousePositionControl);

    features = new ol.Collection();
    featureOverlay = new ol.layer.Vector({
        source : new ol.source.Vector({
            features : features
        }),
        style : new ol.style.Style({
            fill : new ol.style.Fill({
                color : 'rgba(255, 255, 255, 0.05)'
            }),
            stroke : new ol.style.Stroke({
                color : '#ffcc33',
                width : 2
            }),
            image : new ol.style.Circle({
                radius : 7,
                fill : new ol.style.Fill({
                    color : '#ffcc33'
                })
            })
        })
    });
    featureOverlay.setMap(map);
    //初始化选中事件
    initSelectClick();
})

//查找区域列表
function listRegionsCombobox(){
    $.ajax({
        type: "POST",
        url: "listRegionsCombobox",
        contentType: "application/json; charset=utf-8",
        success: function(data){
            var regions='<option value="0" >-请选择区域-</option>';
            if(data.resObject!=null){
                var objs=data.resObject;
                for(var o in objs){
                    regions+='<option value="'+objs[o].id+'" >'+objs[o].name+'</option>';
                }
                $('#targetLabel').html('绑定区域');
                $('#targetId').html(regions);
            }
        },
        error: function(){
            alert("系统异常！");
        }
    });
}


//查找定位基站列表
function listDwjzsCombobox(){
    $.ajax({
        type: "POST",
        url: "listDwjzsCombobox",
        contentType: "application/json; charset=utf-8",
        success: function(data){
            var dwjzs='<option value="0" >-请选择基站-</option>';
            if(data.resObject!=null){
                var objs=data.resObject;
                for(var o in objs){
                    dwjzs+='<option value="'+objs[o].id+'" >'+objs[o].name+'</option>';
                }
                $('#targetLabel').html('绑定基站');
                $('#targetId').html(dwjzs);
            }
        },
        error: function(){
            alert("系统异常！");
        }
    });
}

//查找激活器列表
function listJihuoqisCombobox(){
    $.ajax({
        type: "POST",
        url: "listJihuoqisCombobox",
        contentType: "application/json; charset=utf-8",
        success: function(data){
            var jihuoqis='<option value="0" >-请选择激活器-</option>';
            if(data.resObject!=null){
                var objs=data.resObject;
                for(var o in objs){
                    jihuoqis+='<option value="'+objs[o].id+'" >'+objs[o].name+'</option>';
                }
                $('#targetLabel').html('绑定激活器');
                $('#targetId').html(jihuoqis);
            }
        },
        error: function(){
            alert("系统异常！");
        }
    });
}

//初始化选中事件
var selectClick=null;
function initSelectClick(){
    if(selectClick!=null){
        map.removeInteraction(selectClick);
    }
    //选择事件
    selectClick = new ol.interaction.Select({
        condition: ol.events.condition.click,
        style:selectStyle,

    });
    map.addInteraction(selectClick);
    //选择事件
    selectClick.on('select', function(evt) {
        var selected=evt.selected;
        getInfo(selected);
        //气泡
        if (selected !=null) {
            var coordinate = evt.coordinate;
            for (var s in selected){
                //console.info(c+" = "+feature[c])
                var select=selected[s];
                if(selected[s].get("type")!=1 && selected[s].get("type")!=2){
                    var content=getItemById(selected[s].get("id"),selected[s].get("type"));
                    console.info("content="+content);
                    if(content!=""){
                        $('#popup-content').html(content);
                        document.getElementById("popup").style.left="-50px";
                        overlay = new ol.Overlay(({
                            element: document.getElementById('popup'),
                            autoPan: true,
                            autoPanAnimation: {
                                duration: 250   //当Popup超出地图边界时，为了Popup全部可见，地图移动的速度.
                            }
                        }));
                        overlay.setPosition(selected[s].getGeometry().getCoordinates());
                        map.addOverlay(overlay);
                        $('#popup-closer').on('click', function (event) {
                            if(overlay!=null){overlay.setPosition(undefined);}
                            $('#popup-closer').blur();
                            return false;
                        });// 点击关闭的按钮
                    }


                }

            }
        }
    });
}
//获取元素
function getInfo(selected){
    var selId,selName;
    for(var i=0;i<selected.length;i++){
        var feature=selected[i];
        //selectStyle.getText().setText( feature.get('name'));
        var id=feature.getId();
        selId=id;
        selName=feature.getProperties().name;
        if(!id){
            id=feature.getProperties().id;
        }
        ////console.info(selected);
//		//console.info(id);
//		//console.info(selName);
//		//console.info(feature.getProperties());
        selectObj.id=id;
        selectObj.name=selName;
        selectObj.selected=true;
//		//console.info(feature.get("type"));
        selectObj.type=feature.getProperties().type;
        selectObj.obj=selected[i];
        selectStyle.getText().setText( feature.get('name'));
        //alert(feature.getProperties().type);
        //alert(selectObj.type);
        if('sxt'==selectObj.type){
            ////console.info(selectStyle.getImage());
        }
    }
    //取消选择
    if(selected.length==0){
        selectObj.id="";
        selectObj.name="";
        selectObj.selected=false;
        selectObj.type="";
    }
    //console.info(selectObj);
}


// 绘制区域
var draw; // global so we can remove it later
function drawInteractionPolygon() {
    draw = new ol.interaction.Draw({
        features : features,
        type : 'Polygon'
    });
    map.addInteraction(draw);
}

// 保存区域
function saveInteractionPolygon() {
    listRegionsCombobox();
    map.removeInteraction(draw);
    ////console.info('getFeatures='+featureOverlay.getSource().getFeatures());
    //查找区域列表
    listRegionsCombobox();
    var format = new ol.format.GeoJSON();
    var ffs = format.writeFeatures(featureOverlay.getSource().getFeatures());
    ////console.info('ffs='+ffs);
    $('#type').val(1); //1表示绘制区域绑定
    $('#data').val(ffs);
    $('#myModal').modal('show');
}

// 显示区域
var region_vector = null;
function showInteractionPolygon() {
    //区域颜色
    var regionStyle = new ol.style.Style({
        fill : new ol.style.Fill({ // 矢量图层填充颜色，以及透明度
            color : 'rgba(0, 0, 255, 0.15)'
        }),
        stroke : new ol.style.Stroke({ // 边界样式
            color : '#319FD3',
            width : 1
        }),
        text : new ol.style.Text({ // 文本样式
            font : '14px Calibri,sans-serif',
            fill : new ol.style.Fill({
                color : '#000'
            }),
            stroke : new ol.style.Stroke({
                color : '#fff',
                width : 3
            })
        })
    });
    hideInteractionPolygon();//隐藏区域
    region_vector = new ol.layer.Vector({
        source : new ol.source.Vector({
            url : 'getRegionsData',// 110100.json bei_jing.geo.json b1.json
            format : new ol.format.GeoJSON()
        }),
        style : function(feature, resolution) {
            var id = feature.getId();
            var name = feature.get('name');
            //console.info(feature);
            //console.info(name+","+color);
            //console.info("name="+name);
            var color = feature.get('color');
            regionStyle.getText().setText(feature.get('name'));
            regionStyle.getFill().setColor(getRgba(color, 0.2));
            return [ regionStyle ];
        }
    });
    //console.info("regionObj="+JSON.stringify(regionObj));
    ////console.info("region_vector="+JSON.stringify(region_vector));
    for(var rv in region_vector){
        //console.info(rv+"="+region_vector[rv]);
    }
    addLayer(regionObj,region_vector);
}
//隐藏区域图层
function hideInteractionPolygon(){
    if(regionObj.layer){
        removeLayer(regionObj);
    }
}
//添加图层时，删除对应obj的layer ,style,点击事件
function addLayer(obj,layer){
    obj.layer=layer;
    map.addLayer(layer);
}
// 删除图层时，删除对应obj的layer ,style,点击事件
function removeLayer(obj){
    map.removeLayer(obj.layer);
    obj.layer=null;
    initSelectClick();
}





// 绘制中心点
function drawCenterPoint() {
    cleanInteraction();
    draw = new ol.interaction.Draw({
        features : features,
        type : 'Point'
    });
    map.addInteraction(draw);
}

// 保存中心点
function saveCenterPoint() {
    listRegionsCombobox();
    map.removeInteraction(draw);
    //console.info(featureOverlay.getSource().getFeatures());
    var format = new ol.format.GeoJSON();
    var ffs = format.writeFeatures(featureOverlay.getSource().getFeatures());
    //console.info('ffs='+ffs);
    $('#type').val(2); //2表示绘制中心点绑定
    $('#data').val(ffs);
    $('#myModal').modal('show');
}

//显示中心点
var center_vector = null;
function showCenterPoint() {
    var centerStyle = new ol.style.Style({
        text : new ol.style.Text({ // 文本样式
            font : '14px Calibri,sans-serif',
            fill : new ol.style.Fill({
                color : '#000'
            }),
            stroke : new ol.style.Stroke({
                color : '#fff',
                width : 3
            }),
            offsetX : -50,
            offsetY : 50
        }),
        image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
            ({
                opacity : 0.95,
                 src :  $("#contextPath").val()+'/userfiles/points/point24.png'
            }))
    });
    hideCenterPoints();
    center_vector = new ol.layer.Vector({
        source : new ol.source.Vector({
            url : 'getCenterPointData',// 110100.json bei_jing.geo.json b1.json
            format : new ol.format.GeoJSON()
        }),
        style : function(feature, resolution) {
            return [ centerStyle ];
        }
    });
    addLayer(centerPointObj,center_vector);
}
//隐藏中心点
function hideCenterPoints(){
    if(centerPointObj.layer){
        removeLayer(centerPointObj);
    }
}





// 绘制基站
function drawBaseStation() {
    cleanInteraction();
    draw = new ol.interaction.Draw({
        features : features,
        type : 'Point'
    });
    map.addInteraction(draw);
}

// 保存基站
function saveBaseStation() {
    listDwjzsCombobox();
    map.removeInteraction(draw);
    //console.info(featureOverlay.getSource().getFeatures());
    var format = new ol.format.GeoJSON();
    var ffs = format.writeFeatures(featureOverlay.getSource().getFeatures());
    //console.info('ffs='+ffs);
    $('#type').val(3); //3表示绘制基站绑定
    $('#data').val(ffs);
    $('#myModal').modal('show');
}
//显示基站点
var base_vector = null;
function showBaseStation() {
    var baseStyle = new ol.style.Style({
        text : new ol.style.Text({ // 文本样式
            font : '14px Calibri,sans-serif',
            fill : new ol.style.Fill({
                color : '#000'
            }),
            stroke : new ol.style.Stroke({
                color : '#fff',
                width : 3
            }),
            offsetX : -50,
            offsetY : 50
        }),
        image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
            ({
                opacity : 0.95,
                src : $("#contextPath").val()+'/userfiles/points/base24.png'
            }))
    });
    hideBaseStation();
    base_vector = new ol.layer.Vector({
        source : new ol.source.Vector({
            url : 'getBaseStationPointData',// 110100.json bei_jing.geo.json b1.json
            format : new ol.format.GeoJSON()
        }),
        style : function(feature, resolution) {
            return [ baseStyle ];
        }
    });
    addLayer(baseStationObj,base_vector);
}
//隐藏基站点
function hideBaseStation(){
    if(baseStationObj.layer){
        removeLayer(baseStationObj);
    }
}


// 绘制激活器
function drawActivator() {
    cleanInteraction();
    draw = new ol.interaction.Draw({
        features : features,
        type : 'Point'
    });
    map.addInteraction(draw);
}

// 保存激活器
function saveActivator() {
    listJihuoqisCombobox();
    map.removeInteraction(draw);
    //console.info(featureOverlay.getSource().getFeatures());
    var format = new ol.format.GeoJSON();
    var ffs = format.writeFeatures(featureOverlay.getSource().getFeatures());
    //console.info('ffs='+ffs);
    $('#type').val(4); //4表示绘制激活器绑定
    $('#data').val(ffs);
    $('#myModal').modal('show');
}

//显示激活器点
var jihuoqi_vector = null;
function showActivator() {
    var activatorStyle = new ol.style.Style({
        text : new ol.style.Text({ // 文本样式
            font : '14px Calibri,sans-serif',
            fill : new ol.style.Fill({
                color : '#000'
            }),
            stroke : new ol.style.Stroke({
                color : '#fff',
                width : 3
            }),
            offsetX : -50,
            offsetY : 50
        }),
        image : new ol.style.Icon(/** @type {olx.style.IconOptions} */
            ({
                opacity : 0.95,
                src : $("#contextPath").val()+'/userfiles/points/jihuoqi24.png'
            }))
    });
    hideActivator();
    jihuoqi_vector = new ol.layer.Vector({
        source : new ol.source.Vector({
            url : 'getActivatorPointData',// 110100.json bei_jing.geo.json b1.json
            format : new ol.format.GeoJSON()
        }),
        style : function(feature, resolution) {
            return [ activatorStyle ];
        }
    });
    addLayer(activatorObj,jihuoqi_vector);
}
//隐藏基站点
function hideActivator(){
    if(activatorObj.layer){
        removeLayer(activatorObj);
    }
}

function saveMapConfigData(){
    if($("#type").val() == "" || $("#type").val() ==0){
        toastr.error('请确认保存的配置数据','提示')
        return;
    }
    if($("#targetId").val() == "" || $("#targetId").val() ==0){
        toastr.error('请选择绑定的对象','提示')
        return;
    }
    if($("#data").val() == 0){
        toastr.error('请选择角色','提示');
        return;
    }

    $("#dataForm").submit();
    $('#myModal').modal('hide');
    $("#type").val(0);
    $("#data").val('');
}

function deleteSelectObj(type_){
    //alert(selectObj);
    //alert(selectObj.selected);
    //alert(selectObj.type);
    if(selectObj && selectObj.selected && selectObj.type==type_){
        var obj={};
        obj["id"]=selectObj.id;
        obj["type"]=type_;
        var jsonInfo = JSON.stringify(obj);
        ////console.info("jsonInfo="+jsonInfo);
        $.ajax({
                type: "POST",
                url: "deleteMapConfigData",
                data : jsonInfo,
                dataType: "json",
                contentType: "application/json; charset=utf-8",
                success: function(data){
                    //删除完重新加载即可
                    if(1==type_){
                        showInteractionPolygon();
                    }else if(2==type_){
                        showCenterPoint();
                    }else if(3==type_){
                        showBaseStation();
                    }else if(4==type_){
                        showActivator();
                    }
                },
                error: function(){
                    alert("系统异常！");
                }
            });
    }else{
        if(1==type_){
            toastr.error('请选择一个区域','提示')
            return;
        }else if(2==type_){
            toastr.error('请选择一个中心点','提示')
            return;
        }else if(3==type_){
            toastr.error('请选择一个基站','提示')
            return;
        }else if(4==type_){
            toastr.error('请选择一个激活器','提示')
            return;
        }

    }

}
//根据ID和type查找元素
function getItemById(id,type){
    var obj=new Object();
    obj["id"]=id;
    obj["type"]=type;
    var jsonInfo=JSON.stringify(obj);
    console.info("jsonInfo"+jsonInfo);
    var contentHtml='';
    $.ajax({
        type: "POST",
        url: "getItemById",
        data:jsonInfo,
        dataType: "json",
        async:false,
        contentType: "application/json; charset=utf-8",
        success: function(data){
            console.info("data="+JSON.stringify(data))
            if(data.resObject!=null){
                contentHtml=getPopupContent(data.resObject,type)
            }
        },
        error: function(){
            console.info("系统异常！");
        }
    });
    return contentHtml;
}

//生成popup内容
function getPopupContent(obj,type){
    var contentHtml='';
    if(type==3){
        contentHtml='名称:'+obj.name+"<br>"+
            'IP:'+obj.ip+"<br>"+
            '端口:'+obj.port+"<br>"+
            '类型:'+obj.typeName+"<br>";
    }else if(type==4){
        contentHtml='区域:'+obj.regionName+"<br>"+
            '编号:'+obj.sbbh+"<br>"+
            '组名:'+obj.groupName+"<br>"+
            '序号:'+obj.groupNo+"<br>"+
            '类型:'+obj.sblxName+"<br>";
    }
    return contentHtml;

}
//清空所有图层
function cleanInteraction() {
    featureOverlay.getSource().clear();
}


//设置选中的地图层
function selectOnemapTile(selectMapTilesId){
    //alert("selectMapTilesId="+selectMapTilesId);
    $.ajax({
        type: "POST",
        url: "setSelectMapTiles?id="+selectMapTilesId,
        contentType: "application/json; charset=utf-8",
        success: function(msg){
            window.location.reload();
        },
        error: function(){
            alert("系统异常！");
        }
    });
}

var isFull=true;
function OpenFullScreen() {
    //window.location=$("#contextPath").val() +"/rfid/maplocation/mapLocationManage";
    if(isFull){
        $("#fullScreenBtn").text("退出全屏");
        try{
            fullScreen();
        }catch (e)
        {
        }
    }else{
        $("#fullScreenBtn").text("全屏显示");
        try{
            exitFullScreen();
        }catch (e)
        {

        }
    }
    isFull=!isFull;
}